package com.xs.gis.cover.coverImpl;

import com.xs.gis.cover.FileCover;
import com.xs.gis.domain.geojson.GeoFeature;
import com.xs.gis.domain.geojson.GeoJsonFeature;
import com.xs.gis.enums.CoverConstant;
import com.xs.gis.util.GisCommonUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.gdal.gdal.gdal;
import org.gdal.ogr.DataSource;
import org.gdal.ogr.Driver;
import org.gdal.ogr.Layer;
import org.gdal.ogr.ogr;
import org.gdal.osr.SpatialReference;

import java.util.List;

import static com.xs.gis.enums.CoverConstant.DIVER_SQLITE;

/**
 * @description:
 * @author: w
 * @create: 2023-08-18 10:09
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SqliteCover implements FileCover {



    private String defaultEpsgCode = "4490";

    @Override
    public String featureToFile(GeoJsonFeature feature, String filePath) {

        gdal.AllRegister();
        ogr.RegisterAll();


        Driver driver = ogr.GetDriverByName(DIVER_SQLITE);
        if (driver == null) {
            throw new RuntimeException("驱动不可用!");
        }
        DataSource dataSource = driver.CreateDataSource(filePath);

        List<GeoFeature> features = feature.getFeatures();
        //创建图层
        String epsgCode = StringUtils.isBlank(feature.getEpsgCode()) ? defaultEpsgCode : feature.getEpsgCode();
        Layer gdbLayer = GisCommonUtils.createLayer(feature, dataSource, epsgCode, CoverConstant.SQLITE_IGNORE_FIELD);
        //添加数据
        GisCommonUtils.addGdbData(features, gdbLayer, epsgCode);
        //释放
        gdbLayer.delete();
        dataSource.delete();
        gdal.GDALDestroyDriverManager();

        return filePath;
    }


    /***
     * 文件解析为feature
     * @param filePath
     * @return
     */
    @Override
    public GeoJsonFeature fileToFeature(String filePath) {

        gdal.AllRegister();
        ogr.RegisterAll();
        DataSource dataSource = ogr.Open(filePath);

        GeoJsonFeature geoJsonFeature = new GeoJsonFeature();

        if (dataSource != null) {
            Layer layer = dataSource.GetLayerByIndex(0);
            if (layer != null) {
                // 遍历图层中的特征
                layer.ResetReading();
                org.gdal.ogr.Feature feature;

                geoJsonFeature.setLayerName(layer.GetName());

                SpatialReference spatialReference = layer.GetSpatialRef();
                String epscCode = spatialReference == null ? defaultEpsgCode : spatialReference.GetAttrValue("AUTHORITY", 1);

                List<GeoFeature> features = GisCommonUtils.layerFeatureToFeature(epscCode, geoJsonFeature, layer);
                geoJsonFeature.setFeatures(features);
                layer.delete();
            }
        }
        dataSource.delete();
        gdal.GDALDestroyDriverManager();

        return geoJsonFeature;
    }



}
